<?php
/**
 * @author qingyu8@staff.weibo.com
 * @date 2018/04/19
 */

namespace backend\controllers;

use common\models\BookerItem;
use common\models\Cabin;
use common\models\Occupancy;
use common\models\TableField;
use common\models\Tour;
use common\models\Trip;
use common\models\Boat;
use common\tool\FormField;
use common\tool\Oss;
use Yii;
use yii\data\Pagination;
use yii\helpers\ArrayHelper;
use yii\web\Controller;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;
use common\models\LoginForm;
use yii\web\Response;

class EditController extends Controller {
    public function actionField() {
        $fields = TableField::getList();
        header('Content-type: application/json');
        echo json_encode($fields);
    }

    public function actionEdit() {
        $type = Yii::$app->request->get('type', 'boat');
        $id = Yii::$app->request->get('id');
        $item = [];
        switch ($type) {
            case 'boat':
                $item = Boat::getOne("id=$id");
                break;
            case 'trip':
                $item = Trip::getOne("id=$id");
                break;
            case 'tour':
                $item = Tour::getOne("id=$id");
                break;
            case 'cabin':
                $item = Cabin::getOne("id=$id");
                break;
            case 'occupancy':
                $item = Occupancy::getOne("id=$id");
                break;
        }
        foreach ($item as $k => $v) {
            if (is_string($v)) {
                $item[$k] = htmlspecialchars($v);
            }
        }
        return $this->render('edit', [
            'type' => $type,
            'item' => $item
        ]);
    }

    public function actionList() {
        $type = Yii::$app->request->get('type', 'boat');
        $condition = [];
        $data = [];
        switch ($type) {
            case 'boat':
                $total = Boat::getScalar('', 'count(*) as c');
                $pages = new Pagination(['totalCount' => $total]);
                $data = Boat::getList($condition, '*', 'id', $pages->offset, $pages->limit);
                break;
            case 'trip':
                $total = Trip::getScalar('', 'count(*) as c');
                $pages = new Pagination(['totalCount' => $total]);
                $data = Trip::getList($condition, '*', 'id', $pages->offset, $pages->limit);
                break;
            case 'tour':
                $total = Tour::getScalar('', 'count(*) as c');
                $pages = new Pagination(['totalCount' => $total]);
                $data = Tour::getList($condition, '*', 'id', $pages->offset, $pages->limit);

                $tourIds = implode(',', array_column($data, 'id'));
                $sql = "select distinct dive_trip.tour_id,dive_trip.boat_id,dive_boat.name_en from dive_trip
join dive_boat
on dive_trip.boat_id=dive_boat.id
where tour_id in ($tourIds)";
                $bm = Tour::getDb()->createCommand($sql)->queryAll();
                foreach ($bm as $k => $v) {
                    $bm[$v['tour_id']] = $v;
                }
                foreach ($data as $k => $v) {
                    $data[$k]['boatName'] = $bm[$v['id']]['name_en'] ?? '';
                }
                break;
            case 'cabin':
                $total = Cabin::getScalar('', 'count(*) as c');
                $pages = new Pagination(['totalCount' => $total]);
                $data = Cabin::getList($condition, '*', 'id', $pages->offset, $pages->limit);
                break;
            case 'occupancy':
                $total = Occupancy::getScalar('', 'count(*) as c');
                $pages = new Pagination(['totalCount' => $total]);
                $data = Occupancy::getList($condition, '*', 'id', $pages->offset, $pages->limit);
                break;
            case 'bookerItem':
                $total=63;
                $pages = new Pagination(['totalCount' => $total,'PageSize'=>63]);
                $data=BookerItem::getList();
                break;
        }
        return $this->render('list', [
            'type' => $type,
            'data' => $data,
            'pages' => $pages,
            'total' => $total,
        ]);
    }

    public function actionTranslate(){
        if ($map = Yii::$app->request->post('map')) {
            $map = FormField::rowData($map, '|');
            $o = 0;
            $limit = 20;
            while ($list = Boat::getList('', 'id,policy,policy_cn', 'id', $o, $limit)) {
                foreach ($list as $k => $v) {
                    $v['policy'] = str_replace(array_column($map, 0), array_column($map, 1), $v['policy']);
                    Boat::update(['policy_cn' => $v['policy']], "id={$v['id']}");
                }
                $o += $limit;
            }
            Yii::$app->response->format = Response::FORMAT_JSON;
            return ['err' => 0];
        }
        return $this->render('translate');
    }

    public function actionSavebookeritem() {
        Yii::$app->response->format = Response::FORMAT_JSON;
        $data = Yii::$app->request->post();
        $id = ArrayHelper::remove($data, 'id');
        BookerItem::update([
            'name_cn' => $data['name_cn'],
        ], "id=$id");
        return ['err' => 0];
    }

    public function actionSave() {
        Yii::$app->response->format = Response::FORMAT_JSON;
        $type = Yii::$app->request->get('type', 'boat');
        $data = Yii::$app->request->post();
        $id = ArrayHelper::remove($data, 'id');
        if(empty($id)){return['err'=>1,'param err'];}

        if (!empty($data['boat_batch_countries'])) {
            Boat::update(['countries_cn' => $data['countries_cn']], "countries=:countries", [':countries' => $data['countries'],]);
            unset($data['boat_batch_countries']);
        }
        if (!empty($data['boat_batch_policy'])) {
            Boat::update(['policy_cn' => $data['policy_cn']], "policy=:policy", [':policy' => $data['policy'],]);
            unset($data['boat_batch_policy']);
        }
        if (!empty($data['boat_batch_languages'])) {
            Boat::update(['languages_cn' => $data['languages_cn']], "languages=:languages", [':languages' => $data['languages'],]);
            unset($data['boat_batch_languages']);
        }
        if (!empty($data['trip_batch_name'])) {
            Trip::update(['name_cn' => $data['name_cn']], "name_en=:name_en", [':name_en' => $data['name_en']]);
            unset($data['trip_batch_name']);
        }
        if (!empty($data['tour_batch_name'])) {
            Tour::update(['name_cn' => $data['name_cn']], "name_en=:name_en", [':name_en' => $data['name_en'],]);
            unset($data['tour_batch_name']);
        }
        if (!empty($data['tour_batch_desc'])) {
            Tour::update(['desc_cn' => $data['desc_cn']], "desc_en=:desc_en", [':desc_en' => $data['desc_en']]);
            unset($data['tour_batch_desc']);
        }
        if (!empty($data['tour_batch_included'])) {
            Tour::update(['included_cn' => $data['included_cn']], "included=:included", [':included' => $data['included']]);
            unset($data['tour_batch_included']);
        }
        if (!empty($data['tour_batch_notincluded'])) {
            Tour::update(['notincluded_cn' => $data['notincluded_cn']], "notincluded=:notincluded", [':notincluded' => $data['notincluded']]);
            unset($data['tour_batch_notincluded']);
        }
        if (!empty($data['tour_batch_departure'])) {
            Tour::update(['departure_cn' => $data['departure_cn']], "departure_location=:departure_location", [':departure_location' => $data['departure_location']]);
            unset($data['tour_batch_departure']);
        }
        if (!empty($data['tour_batch_arrival'])) {
            Tour::update(['arrival_cn' => $data['arrival_cn']], "arrival_location=:arrival_location", [':arrival_location' => $data['arrival_location']]);
            unset($data['tour_batch_arrival']);
        }
        if (!empty($data['cabin_batch_name'])) {
            Cabin::update(['name_cn' => $data['name_cn']], "name_en=:name_en", [':name_en' => $data['name_en']]);
            unset($data['cabin_batch_name']);
        }
        if (!empty($data['cabin_batch_deck'])) {
            Cabin::update(['deck_cn' => $data['deck_cn']], "deck=:deck", [':deck' => $data['deck']]);
            unset($data['cabin_batch_deck']);
        }
        if (!empty($data['cabin_batch_bedding'])) {
            Cabin::update(['bedding_cn' => $data['bedding_cn']], "bedding=:bedding", [':bedding' => $data['bedding']]);
            unset($data['cabin_batch_bedding']);
        }

        switch ($type) {
            case 'boat':
                Boat::update($data, "id=$id");
                break;
            case 'trip':
                $item = Trip::update($data, "id=$id");
                break;
            case 'tour':
                $item = Tour::update($data, "id=$id");
                break;
            case 'cabin':
                $item = Cabin::update($data, "id=$id");
                break;
            case 'occupancy':
                $item = Occupancy::update($data, "id=$id");
                break;
        }
        foreach ($data as $k => $v) {
            TableField::update([
                'edited' => 1,
                'edit_time' => date('Y-m-d H:i:s'),
            ], "`table`='dive_$type' AND `field`='$k'");
        }
        return ['err' => 0];
    }

    public function actionSource() {
        $id = Yii::$app->request->get('id');
        $tourId = Yii::$app->request->get('tourId');
        $cabinId=Yii::$app->request->get('cabinId');
        if ($id) {
            $url = Boat::getScalar("id=$id", 'booker_url');
        } elseif($tourId) {
            $diveBoatId = Trip::getScalar("tour_id=$tourId", 'boat_id');
            $url = Boat::getScalar("id=$diveBoatId", 'booker_url');
        }else{
            $diveBoatId = Cabin::getScalar("id=$cabinId",'boat_id');
            $url = Boat::getScalar("id=$diveBoatId", 'booker_url');
        }
        header("Location: $url");
    }

    public function actionOss() {
        Oss::listObjects();
    }
}
